package com.cn.yang.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.yang.model.UserModel;
import com.cn.yang.service.UserService;
import com.cn.yang.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/back/user/updateUser")
public class UpdateByIdServlet extends HttpServlet {
    //查询数据，返回==============
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Integer id = Integer.valueOf(req.getParameter("id"));
        UserService userService = new UserServiceImpl();
        UserModel userModel = userService.selectById(id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userModel",userModel);

        resp.getWriter().println(jsonObject);
    }
    // 更新数据库===========================================================
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Integer id = Integer.valueOf(req.getParameter("id"));
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        String sex = req.getParameter("sex");
        String birthday = req.getParameter("birthday");
        String hobby = req.getParameter("hobby");
        String introduce = req.getParameter("introduce");
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String updatetime = sdf.format(d);

        UserModel userModel = new UserModel();
        userModel.setId(id);
        userModel.setPassword(password);
        userModel.setPhone(phone);
        userModel.setSex(sex);
        userModel.setBirthday(birthday);
        userModel.setHobby(hobby);
        userModel.setIntroduce(introduce);
        userModel.setUpdatetime(updatetime);

        UserService userService = new UserServiceImpl();
        int  result = userService.updateById(userModel);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result",result);
        resp.getWriter().println(jsonObject);

    }
}
